package dk.mga.androidExplore.sensor;

import dk.mga.androidExplore.*;
import dk.mga.androidExplore.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class SensorMonitor extends Activity {
	
	private final String tag = "myLog";
	public static final String SENSOR_TYPE = "Sensor";
	private SensorReader sensorReader;
    private boolean started = false;
	private PowerManager pm;
	private PowerManager.WakeLock wl;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		int sensType = getIntent().getIntExtra(SENSOR_TYPE, Sensor.TYPE_ACCELEROMETER);// if not set show acc. sensors
		setContentView(R.layout.monitor3sensor);

		CharSequence[] headlines = null;
		if (sensType == Sensor.TYPE_ACCELEROMETER) {
			headlines = getResources().getTextArray(R.array.acc_headlines);
		} else if (sensType == Sensor.TYPE_ORIENTATION) {
			headlines = getResources().getTextArray(R.array.pos_headlines);			
		} else {
			return;// before 'headlines' causes a null pointer exception
		}
		TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01);

		Multiplexer mplx = new Multiplexer();
		for (int i = 0; i < headlines.length; i++) {
			Log.d(tag, "tl.getChildCount() "+tl.getChildCount()+" i ="+i);
			TableRow tr = (TableRow) tl.getChildAt(i);
			FrameLayout fl = (FrameLayout)tr.getChildAt(0);
			TextView tv = new TextView(this);
			tv.setText(headlines[i]);
			tv.setTextColor(Color.BLUE);
			SensorView v = new SensorView(this, Color.LTGRAY+(0x101010*(i%2)));// increase brightness for every 2nd
			fl.addView(v);
			mplx.addView(v, i);
			fl.addView(tv);
		}
		SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		sensorReader = new SensorReader(sm, sensType);
		sensorReader.registerListener(mplx);
		pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
    }

    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.recorder_menu, menu);
		return true;
	}
    
    
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.findItem(R.id.start).setEnabled(!started);
		menu.findItem(R.id.stop).setEnabled(started);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
	    switch (item.getItemId()) {
	    case R.id.start:
	    	if (!started){
	    		sensorReader.start();
	    		wl.acquire();
	    		started = true;
	    	}
	        break;
	    case R.id.stop:
	    	if (started){
	    		sensorReader.stop();
	    		wl.release();
	    		started = false;
	    	}
	    	break;
	    case R.id.sensor_help:
	    	Uri uri = Uri.parse("http://developer.android.com/reference/android/hardware/SensorEvent.html");
	    	Intent intent = new Intent(Intent.ACTION_VIEW, uri);
	    	startActivity(intent);
	    	break;
	    default:
	    	return false;
	    }
	    return true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (started) {
			wl.release();
		}
		sensorReader.stop();
		started = false;
	}
	
	private class Multiplexer implements ISensorListener {
		private SensorView[] views; 
		Multiplexer(){
			views = new SensorView[3];
		}
		void addView(SensorView v, int index) {
			if (index > 2) throw new IndexOutOfBoundsException("No more than 3 views are supported");
			views[index] = v;
		}
		@Override
		public void setValues(int x, int y, int z, int t) {
			if (views[0] != null) views[0].setXYValues(t, x);
			if (views[1] != null) views[1].setXYValues(t, y);
			if (views[2] != null) views[2].setXYValues(t, z);
		}
		@Override
		public int getResolutionX() {
			if (views[0] == null) {
				throw new RuntimeException("View not initialised");
			}
			else {
				return views[0].getWidth(); // let the 1st represent all views assuming they are equal
			}
		}
		@Override
		public int getResolutionY() {
			if (views[0] == null) {
				throw new RuntimeException("View not initialised");
			}
			else {
				return views[0].getHeight(); // let the 1st represent all views assuming they are equal
			}
		}
		@Override
		public void setOrientValues(float azimuth, float pitch, float roll) {
			double degreeToRad = 2*Math.PI/360;
			if (views[0] != null) views[0].setAngles(azimuth*degreeToRad);
			if (views[1] != null) views[1].setAngles(pitch*degreeToRad);
			if (views[2] != null) views[2].setAngles(roll*degreeToRad);
		}
		
	}

}
